# Create your views here.
import datetime

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User

from player.models import Player, OCBPlayer
from player.forms import LinkPlayerForm

def ocb_idrank(request):
    players = [ocbp.player for ocbp in OCBPlayer.objects.exclude(player__idr_score = None).order_by('-player__idr_score')]
    players.extend([ocbp.player for ocbp in OCBPlayer.objects.filter(player__idr_score = None).order_by('player__nickname')])
    return render(request,'player/idr_rank.html',{'players':players,'date':datetime.date.today})
    
def ocb_influrank(request):
    players = [ocbp.player for ocbp in OCBPlayer.objects.all().order_by('-player__influence_score')]
    return render(request,'player/influ_rank.html',{'players':players,'date':datetime.date.today})

def link_player(request):
    if request.user.is_superuser:
        if request.method == "POST":
            form = LinkPlayerForm(data=request.POST)
            if form.is_valid():
                user_id = request.POST['user']
                player_id = request.POST['player']
                
                user = User.objects.get(id=user_id)
                player = Player.objects.get(id=player_id)
                
                ocbplayer = OCBPlayer.objects.create(user = user,player = player)
                message = "user %s has been linked to player %s"%(ocbplayer.user, ocbplayer.player)
                return render(request,'player/link_player.html',{'message':message,
                                                                             'form':LinkPlayerForm()})
            else :
                return render(request,'player/link_player.html',{'form':form})
        else :
            form = LinkPlayerForm()
            return render(request,'player/link_player.html',{'form':form})
    else :
        return HttpResponseRedirect("/")
